package com.innjia.shiro.realm;

import com.innjia.base.common.Constant;
import com.innjia.base.enums.UserSysRoleEnum;
import com.innjia.sys.entity.*;
import com.innjia.sys.service.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

/**
 * <br>
 * 2017-11-14
 *
 * @author zhouxianglh@gmail.com
 */
public abstract class BaseRealm extends AuthorizingRealm {

    @Autowired
    private RoleService roleService;

    @Autowired
    private MenuService menuService;

    @Autowired
    private UserAdminService userAdminService;

    @Autowired
    private UserTenantService userTenantService;

    @Autowired
    private UserLandlordService userLandlordService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        UserEntity user = (UserEntity) principals.getPrimaryPrincipal();
        if (user != null) {
            //根据用户id查询该用户所有的角色,并加入到shiro的SimpleAuthorizationInfo
            info.addRoles(getRoles(user));
            //查询所有该用户授权菜单，并加到shiro的SimpleAuthorizationInfo 做菜单按钮权限控件
            Set<String> permissions = new HashSet<>();
            List<MenuEntity> menuEntities;
            //超级管理员拥有最高权限
            if (Constant.SUPERR_USER.equals(user.getId())) {
                menuEntities = menuService.queryList(new HashMap<>(2));
            } else {
                //普通帐户权限查询
                menuEntities = menuService.queryByUserId(user.getId());
            }
            menuEntities.forEach(menuEntity -> {
                if (StringUtils.isNotEmpty(menuEntity.getPermission())) {
                    permissions.add(menuEntity.getPermission());
                }
            });
            info.addStringPermissions(permissions);
        }
        return info;
    }

    protected Collection<String> getRoles(UserEntity user) {
        List<String> list = new ArrayList<>();
        List<RoleEntity> roles = roleService.queryByUserId(user.getId(), Constant.YESNO.YES.getValue());
        roles.forEach(roleEntity -> {
            list.add(roleEntity.getId());
        });
        //是否为管理员
        if (user instanceof UserAdminEntity) {
            list.add(UserSysRoleEnum.ROLE_ADMIN);
        } else if (user instanceof UserTenantEntity) {
            //是否为租客
            list.add(UserSysRoleEnum.ROLE_TENANT);
        } else if (user instanceof UserLandlordEntity) {
            //是否为房东
            list.add(UserSysRoleEnum.ROLE_LANDLORD);
        }
        return list;
    }
}
